$(function() {
         
    //初始化用户数据
    init();
    //点赞
    var like_url = jumpUrl+"/like"; 
    $(document).on("click",".onlike",function(e){ 
      if(islogin == "" || islogin == null){
          layer.msg("请登陆后在操作！"); 
      }else{
        var loading = layer.msg('加载中...', {icon: 16});
      	$.post(like_url, {"item_type":item_type,"item_id":id},function(data){
        }, 'json').error(function(data){
              var error =  $.parseJSON(data.responseText);
              layer.msg(error.error_messages.item_type[0]);
      	}).success(function(data) {
            layer.close(loading);
            $('.onlike').addClass('offlike').removeClass('onlike'); 
            layer.msg('点赞成功');	
      	});    
      }	
    });
    getComments();
    $(document).on('click','.moreComent',function(e){
    	getComments();
    });
    //判断是否点赞
    $(document).on('click','.offlike',function(e){
      layer.msg("您已经点过赞了！"); 
    });
    $(document).on('click','.offfavorite',function(e){
      layer.msg("您已经收藏过了！"); 
    });
    if(is_like != null && is_like){
      $('.onlike').addClass('offlike').removeClass('onlike'); 
    }
    //判断是否收藏
  	if(is_collect != null && is_collect){
      $('.onfavorite').addClass('offfavorite').removeClass('onfavorite');
  	}
    //获取文章评论
    function getComments(){
      var loading = '<li><div class="loading">加载中...</div></li>'; 
      $("#page").append(loading);
	    var url_comment_list = jumpUrl+"/article/"+id+"/comment/list?page="+page;
	    $.get(url_comment_list,function(data){
	    }, "json").error(function(data) {
	        layer.msg("请求失败！")
	    }).success(function(data) {
        $(".loading").parent().remove();
	        var obj = data.data;
          console.info(obj)
	  	    var starOnUrl = jumpUrl+"/img/star-on.png";
		      var starOffUrl = jumpUrl+"/img/star-off.png";
          if (obj.length>10) {$(".more").css("display","block")};
	        str = '';
	        for(var i=0; i<obj.length; i++){
            if(obj[i].avatar==null){
             obj[i].avatar = jumpUrl+'/img/dfimg.png'
            }
            str+='<li class="oh">'
                str+='<div class="fl"><img src="'+obj[i].avatar+'" width="100" height="100" style="border-radius: 50%;margin:20px;"></div>'
                str+='<div class="fl" style="width:500px">'
                   str+=' <p class="title-conent">'+obj[i].realname+' - '+obj[i].created_at+' </p>'
                   if(obj[i].comment.length>80){
                      str+='<p class="conent-conent">'+obj[i].comment.substr(0,75)+' ...</p>'
                    }else{
                      str+='<p class="conent-conent">'+obj[i].comment+'</p>'
                    }
                str+='</div>'
           str+='</li>'
    	        }
	        page++;
	        $("#page").append(str);
	    });
    
    }
    //对文章的评论
    $(document).on("click", ".publish-comment", function(){

      var evaluate_comment = $('.inpyt-comp').val();
      var evaluate_score = 5;
      if(evaluate_comment.length < 1){
          layer.msg('提交的内容不能为空！');
          return false;
      }else if(evaluate_comment.length > 300){
        layer.msg('内容不能超过300个字')
        return false;
      }
      var loading = layer.msg('操作中...', {icon: 16});
      $.post(comment_url, {"evaluate_comment":evaluate_comment,"evaluate_score":evaluate_score,"item_id":id},function(data){
        }, 'json').error(function(data){
              var error =  $.parseJSON(data.responseText);
              layer.msg(error.error_messages.item_id[0]);
        }).success(function(data) {
          layer.close(loading);
            layer.msg('评论成功');  
            getComments();
        });
    });


    //对文章的评分
    $(document).on("mouseover", ".star-score img", function(){
    	var index = $(this).index();
    	var	starOnUrl = jumpUrl+"/img/star-on.png";
  	  var	starOffUrl = jumpUrl+"/img/star-off.png";
    	$(this).attr("src",starOnUrl);
    	$(this).prevAll().attr("src",starOnUrl);
    	$(this).nextAll().attr("src",starOffUrl);
    });
    $(document).on("click", ".star-score img", function(){
  		$('#evaluate_score').val($(this).index()+1);		
    })
    
    $(document).on("mouseleave", ".star-score", function(){
  	  var index = parseInt($('.num-score').text());
  	  var starOffUrl = jumpUrl+"/img/star-off.png";
  	  var starOnUrl = jumpUrl+"/img/star-on.png";
  	  $('.star-score img:eq('+index+')').prevAll().attr("src",starOnUrl);
  	  $('.star-score img:eq('+index+')').attr("src",starOffUrl);
  	  $('.star-score img:eq('+index+')').nextAll().attr("src",starOffUrl);	  

  	  });
    
    
    var discuss_form = $("#discuss_form");
    //用户评论
    $(document).on("click",".subComment",function(e){
        if(islogin == "" || islogin == null){
          layer.msg("请登陆后在操作！"); 
        }else{
            var $this = $(this);
            var parent = $this.parent().parent().parent();
            var subContent =$.trim($this.parent().parent().children("#substitutor_content").val());
            var loading = layer.msg('加载中...', {icon: 16});
            var str ="";
            var isUserlvComm = $this.attr("data-id");
      	  	var score = $('#evaluate_score').val();
            if(subContent.length < 1){
                layer.msg('提交的内容不能为空！');
            }else if(score<1){
            	layer.msg('评分在1-5分之间'); 
            }else{
                if(isUserlvComm == 0){
                    $.post(comment_url, discuss_form.serialize(),
                   function(data){
                        
                   },'json').error(function(data) {
                	   
                       var obj = $.parseJSON(data.responseText);
                       layer.msg(obj.message);
                   }).success(function(data){
     
                      var obj = data.data;
                   	  var starOnUrl = jumpUrl+"/img/star-on.png";
                 	  var starOffUrl = jumpUrl+"/img/star-off.png";
                         str = '';
                         	if(obj.avatar==null){
                         		obj.avatar = '/img/user-icon.png'
                         	}
                 			str+='<ol class="reply clear">'
                 			str+='<li class="replyPortrait">'
                 				str+='<img class="" src="'+jumpUrl+'/'+obj.avatar+'" alt="头像" /><br>'
                 				str+='<label>'+obj.realname+'</label>'
                 			str+='</li>'
                 			str+='<li class="replyDetail">'
                 					str+='<span class="replyTime">'+obj.created_at+'</span>&nbsp'
                 					str+='<span class="score">'
                 		            for(var j=1; j<=5; j++){
                 		            	if(j<=obj.score){
                 		            		str+='<img src="'+starOnUrl+'">'
                 		            	}else{
                 		            		str+='<img src="'+starOffUrl+'">'
                 		            	}
                 		            }
                 					str+='</span>'
                 					str+='<div class="replayContents">'+obj.comment+'</div>'
                 			str+='</li>'
                 			str+='</ol>'
                 		 $('.ds-comments-info').hide();
                         $("#page").append(str); 
                   });
                }
            }
          }
        stopDefault(e);
    });

    //律师回复评论
    $(document).on("click",".lv-comment-reply",function(e){
        var lvInfoJson ={
                                "id":"1",
                                "name":"刘心",
                                "img":"/img/case/lvLawyer.png"
                              }; 
        $(".lv-poster-bd").remove();
        var $this = $(this);
        var str ="";
        str+='<div class="lv-poster-bd">'
                str+='<form id="discuss_form" method="post" action="'+discuss_form[0].action+'">'
                    str+='<input type="hidden" name="this_id" value="'+lvInfoJson.id+'">'
                    str+='<input type="hidden" name="user_name" value="'+lvInfoJson.name+'">'
                    str+='<input type="hidden" name="user_img" value="'+lvInfoJson.img+'">'
                    str+='<a class="ds-avatar" href="javascript:void(0);"><img src="'+jumpUrl+lvInfoJson.img+'" alt=""></a>'
                    str+='<div class="content_content">'
                        str+='<textarea placeholder="说点什么吧...." id="substitutor_content" rows="10" cols="50" class="itxtarea" name="content"></textarea>'
                        str+='<pre class="ds-hidden-text"></pre>'
                        str+='<div class="clearfix ds-post-toolbar">'
                            str+='<a href="javascript:void(0);" data-id="1" type="button" class="inpbg subComment" value="">发表评论</a>'
                        str+='</div>'
                    str+='</div>'
                str+='</form>'
           str+='</div>';

           var thislayer =  $this.parent().parent().siblings(".lv-comments-sub")
           thislayer.append(str);

        stopDefault(e);
    });
    
    //收藏文章
    $(document).on("click", ".onfavorite", function(e){
    	var url = jumpUrl+"/collect";
    	var _token = $("input[name='_token']").val();
      if(islogin == "" || islogin == null){
          layer.msg("请登陆后在操作！"); 
      }else{
        var loading = layer.msg('加载中...', {icon: 16});
      	$.post(url,{'collect_type':'3', 'item_id':id, '_token':_token},function(){
      	}, 'json').error(function(data){
  	          var obj = $.parseJSON(data.responseText);
  	          $.each(obj.error_messages, function(i, item){
  	        	  layer.msg(item[0]);
  	          });
      	}).success(function(data){
          layer.close(loading);
      		var obj = data.data;
      			layer.msg('收藏成功');
            $('.onfavorite').addClass('offfavorite').removeClass('onfavorite');
      	// 		$('.favorite').css("background-image","url("+jumpUrl+"/img/star-on.png)")
      	// 		$('.last .count').text(obj);
      	});
      }
    	

    });
    // 一周热文
    how_box();
    function how_box(){
      
      var loading = '<li><div class="loading">加载中...</div></li>'; 
      $(".how-box").append(loading);
      var how_box_url = jumpUrl+"/knowledge/most_liked?order=created_at&rows_per_page=3&class_id=368";
      $.get(how_box_url,function(){

      },'json').error(function(data){

      }).success(function(data){
        
        $(".loading").parent().remove();
        var obj = data.data;
        console.info(obj)
        str = ''
          for(var i=0; i<obj.length; i++){
            str+='<li>'
              str+='<img src="'+obj[i].img+'" width="300" height="140">'
              str+='<p><a href="'+jumpUrl+'knowledge/'+obj[i].id+'/view">'+obj[i].title+'</a></p>'
            str+='</li>'
          }
        $(".how-box").append(str);

      })
    }

    //用户回复评论
    $(document).on("click",".comments-sub-reply",function(e){
        var userInfoJson ={
                                "id":"2",
                                "name":"刘心2",
                                "img":"/img/case/defaultAvatar.png"
                              }; 
        $(".lv-poster-bd").remove();
        var $this = $(this);
        var str ="";
        //获取律师的姓名
        var userName = $this.parent().parent().find(".nickname").eq(0).text();
        str+='<div class="lv-poster-bd">'
                str+='<form id="discuss_form" method="post" action="'+discuss_form[0].action+'">'
                    str+='<input type="hidden" name="this_id" value="'+userInfoJson.id+'">'
                    str+='<input type="hidden" name="user_name" value="'+userInfoJson.name+'">'
                    str+='<input type="hidden" name="user_img" value="'+userInfoJson.img+'">'
                    str+='<a class="ds-avatar" href="javascript:void(0);"><img src="'+jumpUrl+userInfoJson.img+'" alt=""></a>'
                    str+='<div class="content_content">'
                        str+='<textarea placeholder="说点什么吧...." id="substitutor_content" rows="10" cols="50" class="itxtarea" name="content"></textarea>'
                        str+='<pre class="ds-hidden-text"></pre>'
                        str+='<div class="clearfix ds-post-toolbar">'
                            str+='<a href="javascript:void(0);" data-id="1" type="button" class="inpbg subComment" value="">发表评论</a>'
                        str+='</div>'
                    str+='</div>'
                str+='</form>'
           str+='</div>';
           var thislayer =  $this.parent().parent().parent();
           thislayer.append(str);
           var altName = $this.parent().parent().siblings(".lv-poster-bd").children().children().children(".ds-hidden-text");
            $("#commReply").focus();

        stopDefault(e);
    });
    
    //在输入评论的时候把值付给 文本
    $(document).on( "keyup", "form textarea", function(e) {
        var $this = $(this);
        var val = $.trim($this.val());
        $this.siblings(".ds-hidden-text").text(val)
        stopDefault(e);
    })

    
});

    //初始化用户数据的方法
    function init(){
        var userInfoJson ={
                                "id":"0",
                                "name":"小刘心",
                                "img":"/img/defaultmsg1.png"
                              };          
        $("input[name='this_id']:hidden").attr("value",userInfoJson.id);
        $("input[name='user_name']:hidden").attr("value",userInfoJson.name);
        $("input[name='user_img']:hidden").attr("value",userInfoJson.img); 
    }

//获取当前的时间的方法 追加0
function getDateTime()
{ 
    var date = new Date();
    var year = date.getFullYear();       //年
    var month = date.getMonth() + 1;     //月
    var day = date.getDate();            //日
/*    var hh = date.getHours();            //时
    var mm = date.getMinutes();          //分*/
    var str = year + "-";
    if(month < 10)
        str += "0";
    str += month + "-";
    if(day < 10)
        str += "0";
    str += day + " ";
   /* if(hh < 10)
        str += "0";
    str += hh + ":";
    if (mm < 10) str += '0'; 
    str += mm; */
    return(str); 
} 
